import classNames from "classnames";
import React, { useCallback, useState } from "react";
import { EditorFormProps } from "../declare";
import { AddControl } from "./AddControl";
import { LabelAddModal } from "./LabelAddModal";
import { RemoveControl } from "./RemoveControl";

import styles from './style.less'

export function useLabelEditor(props: EditorFormProps) {


  const [vis, setVis] = useState<boolean>(false)
  const handleAdd = useCallback(() => {
    setVis(true)
  }, [])

  const handleClose = useCallback(() => {
    setVis(false)
  }, [])

  const handleOk = useCallback((item) => {
    const value = props.value || []
    value.push(item)
    props.onChange(value.slice(0))
  }, [props])


  const handleRemove = useCallback((item) => {
    const newVal = props.value || {}
        const idx = newVal.findIndex(tx => tx.name === item.name)
        if (idx > -1) {
          newVal.splice(idx, 1)
        }
        props.onChange(newVal.slice(0))
  }, [props])

  return {
    handleAdd,
    handleOk,
    handleClose,
    handleRemove,
    vis
  }
}


/**
 * 公告编辑器
 * @param props 
 */
export function LabelEditor(props: EditorFormProps) {

  const { handleAdd, vis, handleClose, handleOk, handleRemove } = useLabelEditor(props)
  return (
    <div className={styles["editor"]}>

      <div className={styles['label-list']}>
        {
          props.value?.map((tx: any) => (
            <div className={styles['label-item']}>
              <div className={classNames(styles["label-item-img"], {
                [styles['label-item-img-full']]: props.isEntry
              })}>
                <img src={tx.image_url} />
              </div>
              <div className={styles["label-item-title"]}>
                {tx.name}
              </div>
              <RemoveControl
                onRm={() => {
                  handleRemove(tx)
                }}
              />
            </div>
          ))
        }
      </div>
      <AddControl
        onAdd={handleAdd}
      />
      <LabelAddModal
        onOk={handleOk}
        open={vis}
        onClose={handleClose}
        isEntry={props.isEntry}
      />
    </div>
  )
}